package com.ep.thirdPlatformProject.oa.util;

import cn.hutool.core.util.NumberUtil;
import com.ep.thirdPlatformProject.oa.entity.OAResult;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.Unmarshaller;
import lombok.extern.slf4j.Slf4j;
import java.io.StringReader;
import java.io.Writer;
import java.lang.reflect.Field;
import java.util.Arrays;

@Slf4j
public class OAHrmTemplateUtil {


    /**
     * 添加
     */
    public static final String ADD = "add";

    /**
     * 编辑
     */
    public static final String EDIT = "edit";
    /**
     * 删除
     */
    public static final String DELETE = "delete";

    public static String getHrmUserinfoTemplateStr(String beanXml) {
        return """
                <?xml version='1.0' encoding='UTF-8'?>
                <root>
                    <hrmlist>
                        beanXml
                    </hrmlist>
                </root>""".replace("beanXml", beanXml);

    }

    /**
     * 解析实体XML
     *
     * @param t          t
     * @param alias      别名
     * @param omitFields 省略字段
     * @return {@link String }
     */
    public static <T> String parseEntityXml(T t, String alias, String... omitFields) {
        try {

            XStream xStream = new XStream(new XppDriver() {
                public HierarchicalStreamWriter createWriter(Writer out) {
                    return new PrettyPrintWriter(out) {


                        final boolean cdata = true;

                        public void startNode(String name, Class clazz) {
                            super.startNode(name, clazz);
                        }

                        protected void writeText(QuickWriter writer, String text) {
                            if (cdata) {
                                writer.write("<![CDATA[");
                                writer.write(text);
                                writer.write("]]>");
                            } else {
                                writer.write(text);
                            }

                        }

                    };
                }
            });
            xStream.alias(alias, t.getClass());
            Field[] declaredFields = t.getClass().getDeclaredFields();
            boolean hasAction = Arrays.stream(declaredFields).anyMatch(item -> item.getName().equals("action"));
            if (hasAction) {
                xStream.useAttributeFor(t.getClass(), "action");
            }
            for (String omitField : omitFields) {
                xStream.omitField(t.getClass(), omitField);
            }

            String xml = xStream.toXML(t);
            xml = xml.replaceAll("__", "_");
            log.info("parseEntityXml解析后的结果为：{}", xml);
            return xml;
        } catch (
                Exception e) {
            log.error("解析{}失败", t.getClass().getName(), e);
            throw new RuntimeException("解析失败：" + e.getMessage());
        }
    }


    /**
     * 解析响应
     *
     * @param xml xml
     * @return {@link String }
     */
    public static String parseResponseXml(String xml) {
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(OAResult.class);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            OAResult result = (OAResult) unmarshaller.unmarshal(new StringReader(xml));
            log.info("parseResponseXml解析结果为：{}", result);
            if (result.message() == null) {
                return "";
            }
            if (NumberUtil.parseInt(result.message().value()) <= 0) {
                throw new RuntimeException("操作失败了,原因是：" + result.message().content());
            }

            return result.message().content();
        } catch (RuntimeException e) {
            log.error("返回结果小于0，操作数据失败了", e);
            throw e;
        } catch (Exception e) {
            log.error("解析parseResponse失败\uD83D\uDE02", e);
            throw new RuntimeException("解析parseResponse失败:" + e.getMessage());
        }

    }


    public static String getHrmOrgInfoTemplateStr(String beanXml) {
        return """
                <?xml version='1.0' encoding='UTF-8'?>
                <root>
                    <orglist>
                        beanXml
                    </orglist>
                </root>""".replace("beanXml", beanXml);

    }

}
